/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/*************************************************************************
 * File: main.cpp
 *************************************************************************
 *\author: starlove
 *************************************************************************/

#include <codec/python_codec.h>
#include <codec/c_codec.h>
#include <network/network_wrapper.h>
#include <testservice.h>
#include <tools/json_cfg.h>
#include <signal.h>

bool io_stop = false;

void sigfunc(int sig)
{
	if(sig == 2)
	{
		io_stop = true;
	}
};

int main()
{
	signal(2, sigfunc);
	CJsonConfigParser config;
	if(!config.LoadFromFile("./config/test_server.conf"))
	{
		printf("Failed to load cfg %s!", "./config/test_server.conf");
		return -1;
	}

	if(!config.EnterSection("Main"))
	{
		printf("Failed to parse cfg secton %s!", "Main");
		return -1;
	}

	/// cfg value set
	const char *szScriptPath 	= config.GetStrValue("script_path","./");
	const char *szAddr 			= config.GetStrValue("addr","127.0.0.1");
	int uPort 					= config.GetIntValue("port", 8000);
	int ioInterval 				= config.GetIntValue("io_interval", 100);
	int uLimit 					= config.GetIntValue("limit", 1000);
	char data_tp 				= config.GetIntValue("service_type", ePEERDTP_PACKET);

	CPythonMachine machine;
	machine.Initialize();
	if( !machine.Bind(szScriptPath, "test_server") )
	{
		return -1;
	}

	CEventDispatcher ed;
	CMLSENetwork cn;
	CMLSESocket sock;
	CMLSEEventIO io;

	if( !cn.Init() )
	{
		printf("init win32 network libaray fail!\n");
		return -1;
	}
	if( !io.Init() )
	{
		printf("create io-handler fail!\n");
		return -1;
	}
	ed.Init(&io, ioInterval);
	if( !sock.Init(&ed) )
	{
		printf("init socket-controller fail!\n");
		return -1;
	}

	CTestService service(&sock);
	service.SetDataType(data_tp);

	if ( !service.Create(szAddr, uPort, uLimit) )
	{
		return -1;
	}

	service.SetMachine(&machine);

	printf("service running...\n");
	while(!io_stop)
	{
		ed.Lookup();
	}

	ed.Abort();
	service.Destory();
	cn.Destory();
	machine.Finalize();
	printf("\nservice closed!\n");
	return 0;
}
